package com.example.coolweather;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.coolweather.db.SiteDBHelper;
import com.example.coolweather.info.CityInfo;
import com.example.coolweather.info.CountyInfo;
import com.example.coolweather.info.ProvinceInfo;
import com.example.coolweather.util.HttpUtil;
import com.example.coolweather.util.ToastUtil;
import com.example.coolweather.util.Utility;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the  factory method to
 * create an instance of this fragment.
 */
public class ChooseAreaFragment extends Fragment {

    private static final String TAG = "lch-ChooseAreaFragment";
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private ImageView iv_back;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();

    // 数据库实例
    private SiteDBHelper mDBHelper;
    // 省列表
    private List<ProvinceInfo> provinceList;
    //市列表
    private List<CityInfo> cityList;
    //县列表
    private List<CountyInfo> countyList;
    //选中的省份
    private ProvinceInfo selectedProvince;
    // 选中的城市
    private CityInfo selectedCity;
    // 当前选中的级别
    private int currentLevel;


    public ChooseAreaFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "DB create start");
        // 数据库实例
        mDBHelper = SiteDBHelper.getInstance(getContext());
        mDBHelper.openReadLink();
        mDBHelper.openWriteLink();
        Log.d(TAG, "DB create success");

        // 设置状态栏颜色
        Window window = getActivity().getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.parseColor("#FF0000"));
    }

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area,container,false);
        titleText = view.findViewById(R.id.title_text);
        iv_back = view.findViewById(R.id.iv_back);
        listView = view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        // Inflate the layout for this fragment
        return view;
    }

    // 给listView和backButton设置点击事件
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentLevel == LEVEL_PROVINCE) {
                    selectedProvince = provinceList.get(position);
                    queryCities();
                } else if (currentLevel == LEVEL_CITY) {
                    selectedCity = cityList.get(position);
                    queryCounties();
                } else if (currentLevel == LEVEL_COUNTY) {
                    String weatherId = countyList.get(position).weatherId;
                    /*instanceof关键字可以用来判断一个对象是否属于某个类的实例。我们在碎片中调用getActivity()方法，然后配合instanceof关键字，就能轻
                      松判断出该碎片是在MainActivity当中，还是在WeatherActivity当中。如果是在MainActivity当*/
                    if (getActivity() instanceof MainActivity) {
                        Intent intent = new Intent(getActivity(), WeatherActivity.class);
                        intent.putExtra("weather_id", weatherId);
                        intent.putExtra("city_name", countyList.get(position).countyName);
                        startActivity(intent);
                        getActivity().finish();
                    } else if (getActivity() instanceof WeatherActivity) {
                        WeatherActivity activity = (WeatherActivity) getActivity();
                        activity.drawerLayout.closeDrawers();
                        activity.requestWeather(weatherId, countyList.get(position).countyName);
                    }
                }
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentLevel == LEVEL_COUNTY)
                    queryCities();
                else if (currentLevel == LEVEL_CITY)
                    queryProvinces();
            }
        });
        queryProvinces();
    }

    // 查询全国所有的省，优先从数据库查询，如果没有查询到再去服务器上查询
    private void queryProvinces() {
        Log.d(TAG, "queryProvinces");
        titleText.setText("中国");
        iv_back.setVisibility(View.GONE); // 隐藏回退按钮
        provinceList = mDBHelper.queryAllProvinceInfo();
        if (!provinceList.isEmpty()) {
            dataList.clear();
            for (ProvinceInfo info : provinceList) {
                dataList.add(info.provinceName);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            String address = "http://guolin.tech/api/china";
            queryFromServer(address, "province");
        }
    }

    // 查询省内所有的市，优先从数据库查询，如果没有查询到再去服务器上查询
    private void queryCities() {
        Log.d(TAG, "queryCities ");
        titleText.setText(selectedProvince.provinceName);
        iv_back.setVisibility(View.VISIBLE);
        cityList = mDBHelper.queryCityInfoByProvinceId(selectedProvince.id);
        if (!cityList.isEmpty()) {
            dataList.clear();
            for (CityInfo info : cityList) {
                dataList.add(info.cityName);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            int provinceCode = selectedProvince.provinceCode;
            String address = "http://guolin.tech/api/china/" + provinceCode;
            queryFromServer(address, "city");
        }
    }

    // 查询市内所有的县，优先从数据库查询，如果没有查询到再去服务器上查询 完成遍历省市县三级列表的功能
    private void queryCounties() {
        Log.d(TAG, "queryCounties");
        titleText.setText(selectedCity.cityName);
        iv_back.setVisibility(View.VISIBLE);
        Log.d(TAG, "queryCountyInfoByCityId start");
        countyList = mDBHelper.queryCountyInfoByCityId(selectedCity.id);
        Log.d(TAG, "queryCountyInfoByCityId success");
        if (!countyList.isEmpty()) {
            dataList.clear();
            for (CountyInfo info : countyList) {
                dataList.add(info.countyName);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            int provinceCode = selectedProvince.provinceCode;
            int cityCode = selectedCity.cityCode;
            String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }

    // 根据传入的地址和类型从服务器上查询省市县数据
    private void queryFromServer(String address, final String type) {
        Log.d(TAG, "queryFromServer" + type);
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 通过runOnUiThread方法回到主线程处理逻辑
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        ToastUtil.show(getContext(), "加载失败");
                        Log.d(TAG, "queryFromServer 加载失败" + type);
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "queryFromServer onResponse " + type);
                String responseText = response.body().string();
                boolean result = false;
                if ("province".equals(type)) {
                    List<ProvinceInfo> list = Utility.handleProvinceResponse(responseText);
                    result = mDBHelper.insertProvinceInfos(list);
                } else if ("city".equals(type)) {
                    List<CityInfo> list = Utility.handleCityResponse(responseText,selectedProvince.id);
                    result = mDBHelper.insertCityInfos(list);
                } else if ("county".equals(type)) {
                    List<CountyInfo> list = Utility.handleCountyResponse(responseText,selectedCity.id);
                    result = mDBHelper.insertCountyInfos(list);
                }
                if (result) {
                    // 更新UI线程，如果当前线程是UI线程，那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) queryProvinces();
                            else if ("city".equals(type)) queryCities();
                            else if ("county".equals(type)) queryCounties();
                        }
                    });
                }
            }
        });
    }

    // 显示进度对话框
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    // 关闭对话框
    private void closeProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }
}